package mh.demo.jdk.lang;

import java.util.ArrayList;
import java.util.List;

/**
 * 制造堆内存溢出例子
 * 参考《深入理解java虚拟机》一书和网站https://www.baeldung.com/java-heap-dump-capture
 */
public class OutOfMemoryErrorDemo {

    public static void main(String[] args) {
        OutOfMemoryErrorDemo demo = new OutOfMemoryErrorDemo();
        demo.throwOomErrorDemo();
    }

    /**
     * 抛出堆内存异常例子
     * 要在VM options增加如下
     * -Xms20M -Xmx20M -Xlog:gc=info -XX:+HeapDumpOnOutOfMemoryError
     * 也可用-XX:HeapDumpPath=<file-or-dir-path>设置保存路径
     */
    public void throwOomErrorDemo() {
        List<OOMObject> list = new ArrayList<>();
        while (true) {
            list.add(new OOMObject());
        }
    }

    static class OOMObject {
    }

}
